import { queryDictData } from "@/api/systemmanagement";
const state = {
  dictMap: {},
};

const mutations = {
  SET_DICT_DATA: (state, { dictType, data }) => {
    state.dictMap[dictType] = data;
  },
  CLEAR_DICT_DATA: (state, dictType) => {
    if (dictType) {
      delete state.dictMap[dictType];
    } else {
      state.dictMap = {};
    }
  },
};
const actions = {
  // 查询字典数据
  queryDictData({ commit, state }, dictType) {
    return new Promise((resolve, reject) => {
      // 如果已经存在该类型的字典数据，直接返回
      if (state.dictMap[dictType]) {
        resolve(state.dictMap[dictType]);
        return;
      }

      // 调用接口获取数据
      queryDictData({ dictType })
        .then((response) => {
          if (response.code === 0) {
            commit("SET_DICT_DATA", { dictType, data: response.data });
            resolve(response.data);
          } else {
            reject(new Error(response.msg || "获取字典数据失败"));
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 清除字典数据
  clearDictData({ commit }, dictType) {
    commit("CLEAR_DICT_DATA", dictType);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
